$(document).ready(function() {

	var today = new Date();
	$("#fromDate").val(today.getFullYear() + "-" + padDateSingleDigit(today.getMonth() - 1) + "-" + today.getDate());
	$("#toDate").val(today.getFullYear() + "-" + padDateSingleDigit(today.getMonth()) + "-" + today.getDate());
	$("#fromDate").datepicker( {
		dateFormat : 'yy-mm-dd'
	});
	$("#toDate").datepicker( {
		dateFormat : 'yy-mm-dd'
	});

});

function hideAllDataTables() {
	$("#incomeAndExpenseTbl").fadeOut("normal");
	$(".dataRow").each(function() {
		$(this).remove();
	});
}

function fetchData() {
	hideAllDataTables();

	var url = "/index.php?mod=controller1";
	var parms = new Object();
	parms["action"] = "getReport";
	parms["reportType"] = $("#reportType").val();
	parms["toDate"] = $("#toDate").val();
	parms["fromDate"] = $("#fromDate").val();

	$.post(url, parms, function(resultData) {
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			displayReport(resultData, $("#reportType").val());
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function padDescription(description) {
	if (description == "") {
		description = "&nbsp;";
	}
	return description;
}

function getBudgetItemTransactions(row) {

	var url = "/index.php?mod=controller1";
	var parms = new Object();
	parms["action"] = "getBudgetItemTransactions";
	parms["budgetId"] = "current";
	parms["budgetItemId"] = $(row).attr("id");
	parms["toDate"] = $("#toDate").val();
	parms["fromDate"] = $("#fromDate").val();

	$.post(url, parms, function(resultData) {
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			displayBudgetItemTransactions(resultData, $(row).html());
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function displayBudgetItemTransactions(data, itemDescription) {
	$(".transRow").remove();

	$(data).find("Transaction").each(
			function() {
				var date = $(this).find("date").text();
				var description = $(this).find("description").text().replace("\\", "");
				var amount = $(this).find("amount").text();
				var str = '<tr class="transRow"><td>' + date + '</td><td>' + description + '</td><td class="itemAmount">R '
						+ formatCurrency(amount) + '</td></tr>';
				$(str).insertAfter($("#budgetItemTransHeaderRow"));
			});
	calculateTransactionTotal();

	$("#budgetItemTransactionsDiv").dialog( {
		bgiframe : true,
		autoOpen : false,
		width : 600,
		modal : true,
		resizable : false,
		title : itemDescription,
		buttons : {
			OK : function() {
				$(this).dialog("destroy");
			}
		}
	});
	$("#budgetItemTransactionsDiv").dialog("open");
}

function calculateTransactionTotal() {
	var total = 0;
	$(".itemAmount").each(function() {
		var amount = undoCurrencyFormatting($(this).html());
		total += amount;
	});
	$("#total").html("R " + formatCurrency(total.toFixed(2)));
}

function displayReport(data, reportType) {
	var incomeAmount = 0;
	var expenseAmount = 0;

	$("#categoriesTbl,#incomeAndExpenseTbl").hide();
	if (reportType == "incomeAndExpense") {
		$(data).find("Transaction").each(
				function() {
					var rowStr = "";
					var amount = $(this).find('amount').text();

					if ($(this).find("categoryId").text() == 4) {
						amount = eval(amount) * -1;
						amount += "";
					}

					if (eval(amount) < 0) {
						rowStr = '<tr class="dataRow"><td class="spec">' + $(this).find('date').text() + '</td><td scope="spec">'
								+ padDescription($(this).find('description').text())
								+ '</td><td scope="spec">R <label class="incomeRow">' + formatCurrency(correctAmountSign(amount))
								+ '</label></td></tr>';
						$(rowStr).insertAfter("#expenseHeader");
						expenseAmount += correctAmountSign(amount);
					} else {
						rowStr = '<tr class="dataRow"><td class="spec">' + $(this).find('date').text() + '</td><td scope="spec">'
								+ padDescription($(this).find('description').text())
								+ '</td><td scope="spec">R <label class="expenseRow">'
								+ formatCurrency(correctAmountSign(amount)) + '</label></td></tr>';
						$(rowStr).insertAfter("#incomeHeader");
						incomeAmount += correctAmountSign(amount);
					}

					$("#incomeAndExpenseTbl").fadeIn("normal");
				});

		$("#incomeTotal").html(formatCurrency(incomeAmount.toFixed(2)));
		$("#expenseTotal").html(formatCurrency(expenseAmount.toFixed(2)));

	} else if (reportType == "categories") {
		var previousExpenseRow = null;
		var previousIncomeRow = null;
		$(data).find("transaction").each(
				function() {
					var rowStr = '<tr class="dataRow"><td class="spec"><a id="' + $(this).find('id').text()
							+ '" href="#" onclick="getBudgetItemTransactions(this); return false;">'
							+ padDescription($(this).find('description').text()) + '</a></td><td scope="spec">R'
							+ formatCurrency(correctAmountSign($(this).find('amount').text())) + '</td></tr>';
					var rowObj = $(rowStr);
					if (eval($(this).find("amount").text()) < 0) {
						if (previousExpenseRow != null) {
							rowObj.insertAfter(previousExpenseRow);
						} else {
							rowObj.insertAfter("#categoriesExpenseHeader");
						}
						previousExpenseRow = rowObj;
					} else {
						if (previousIncomeRow != null) {
							rowObj.insertAfter(previousIncomeRow);
						} else {
							rowObj.insertAfter("#categoriesIncomeHeader");
						}
						previousIncomeRow = rowObj;
					}

					$("#categoriesTbl").fadeIn("normal");
				});
	}

}